import fs from "fs";
import path from "path";
import pkg from "./package.json"
import packager from "electron-packager"
import _ from "lodash";
import archiver from "archiver";

const srcDir = path.resolve(__dirname, "./src");
const distDir = path.resolve(__dirname, "./dist");
const appDir = distDir + "/app"

const nodeModulesDir = path.resolve(__dirname, "./node_modules");
const distNodeModulesDir = path.resolve(appDir, "./node_modules")

if (fs.existsSync(distDir)) {
    console.log("发现旧dist目录，正在删除");
    fs.rmdirSync(distDir, {recursive: true})
}
if (!fs.existsSync(distDir)) {
    console.log("正在创建应用dist目录");
    fs.mkdirSync(distNodeModulesDir, {recursive: true});
}

console.log("正在复制js文件");
copyDir(srcDir, appDir);

console.log("正在复制node_modules");
Object.entries({
    "@ant-design/icons/dist/index.umd.min.js": "@ant-design/icons/index.js",
    "antd/dist/antd-with-locales.min.js": "antd/index.js",
    // "antd/lib/locale/zh_CN.js": "antd/lib/locale/zh_CN.js",
    "moment/min/moment.min.js": "moment/index.js",
    "node-fetch": "node-fetch",
    "tr46": "tr46",
    "react/umd/react.production.min.js": "react/index.js",
    "react-dom/umd/react-dom.production.min.js": "react-dom/index.js",
    "react-codemirror2/index.js": "react-codemirror2/index.js",
    "codemirror": "codemirror",
    "sudo-prompt/index.js": "sudo-prompt/index.js",
    "lodash/lodash.min.js": "lodash/index.js",
    "@electron/remote/dist/src": "@electron/remote",
    "@electron/remote/package.json": "@electron/remote/package.json",
    "whatwg-url": "whatwg-url",
}).forEach(([src, dist]) => {
    copyDir(`${nodeModulesDir}/${src}`, `${distNodeModulesDir}/${dist}`)
});

console.log("正在生成新的package.json")
const dependencies = _.cloneDeep(pkg.dependencies);
delete dependencies.electron;
fs.writeFileSync(path.resolve(appDir, "./package.json"), JSON.stringify({
    "name": pkg.name,
    "displayName": pkg.displayName,
    "productName": pkg.productName,
    "version": pkg.version,
    "description": pkg.description,
    "main": "index.js",
    "keywords": pkg.keywords,
    "author": pkg.author,
    "license": pkg.license,
    "dependencies": dependencies
}), {encoding: "utf-8"})

console.log("正在构建");
packager({
    out: distDir,
    dir: appDir,
    appCategoryType: "Developer Tools",
    appBundleId: "link.hefang.mhosts",
    appVersion: pkg.version,
    asar: true,
    darwinDarkModeSupport: true,
    platform: ["darwin", "mas", "linux"],
    arch: ["x64"],
    icon: path.resolve(__dirname, "./src/icons/logo"),
    download: {
        mirrorOptions: {
            mirror: "https://mirrors.huaweicloud.com/electron/"
        }
    }
}).then((pathes) => {
    console.log(pathes)
    console.log("构建成功");
    const zipDir = path.resolve(__dirname, "./dist/zips/");
    fs.mkdirSync(zipDir)
    pathes.forEach(app => {
        zip(app, zipDir)
    })
})

// ----------------------工具函数--------------------------
function copyDir(src: string, dist: string) {
    existsOrMkdir(src, dist);
    if (!fs.statSync(src).isDirectory()) {
        fs.copyFileSync(src, dist);
        return;
    }
    const files = fs.readdirSync(src, {encoding: "utf-8"});
    files.forEach(file => {
        const filePath = path.resolve(src, file);
        const distFilePath = path.resolve(dist, file);
        if (fs.statSync(filePath).isDirectory()) {
            copyDir(filePath, distFilePath);
        } else if (!endsWith(file, ".ts", ".tsx", ".map", ".scss", ".md")) {
            fs.copyFileSync(filePath, distFilePath);
        }
    })
}

function existsOrMkdir(src: string, dist: string) {
    const dir = fs.statSync(src).isDirectory() ? dist : path.resolve(dist, "..");
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, {recursive: true})
    }
}

function endsWith(str: string, ...ends: string[]) {
    for (let i = 0; i < ends.length; i++) {
        if (str.endsWith(ends[i])) return true;
    }
    return false;
}

function zip(dir: string, to: string) {
    const pathes = dir.split("/")
    const dirName = pathes[pathes.length - 1];
    const archive = archiver('zip', {zlib: {level: 9}});
    const out = fs.createWriteStream(path.resolve(to, `${dirName}.zip`));
    console.log(`正在打包: ${dirName}`)
    archive.pipe(out);
    archive.directory(dir, dirName);
    archive.finalize().then(() => {
        console.log(`打包成功：${dirName}`)
    });
}